const env = require('./env');
const helper = require('./helper');
const config = require("./config");

const token= {
  init(scene) {
    const _this = this;
    let _token = _this.getStorage();
    let isEmptyToken = !_token;

    if(isEmptyToken || scene) {
      if(scene) {
        helper.log("初始化token-发现新的scene值，删除旧token，重新获取token");
        token.removeStorage();
      }
      _this.get(scene)
      .then(token => {
        _this.setStorage(token);
      })
      .catch(errMsg => {
        console.log(errMsg);
        helper.toastErr(errMsg);
      });
    } else {
      helper.log("初始化token-缓存中已存在token:", _token);
      return _token;
    }
  },
  asyncGetFromStorage() {
    helper.log("发起请求前获取token");
    const _this = this;
    let isTokenEmpty = () => {
      let token = _this.getStorage();
      let isEmpty = !token;
      return isEmpty;
    };
    return new Promise((resolve, reject) => {
      if(isTokenEmpty()) {
        let timer = setInterval(() => {
          if(!isTokenEmpty()) {
            let token = _this.getStorage();
            clearInterval(timer);

            helper.log("等待token返回完毕，token:", token);
            return resolve(token);
          }
          helper.log("等待token返回...");
        }, 300);
      } else {
        let token = _this.getStorage();
        helper.log("发起请求前获取token-从缓存中取得:", token);
        return resolve(token);
      }
    });
  },
  get(scene) {
    const _this = this;
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          helper.log("微信登录结果:", res);
          helper.log("从服务器获取token");
          wx.request({
            url: `${config.DOMAIN[env]}/index/user/token`,
            data: {
              'code': res.code,
              'weixinType': "miniapp",
              'scene': scene || "",
              'markAcount': 'markShop'
            },
            method: "GET",
            header: { 'content-type': 'application/x-www-form-urlencoded', 'version': 'miniapp/0.0.2' },
            success(resp) {
              resp = resp.data;
              helper.log("从服务器获取token结果", resp);
              if(resp.status !== config.RESQ_SUCCESS) {
                console.log("从服务器获取token失败01:", config.RESQ_SUCCESS, resp.msg);
                return reject(resp.msg);
              } else {
                helper.log("从服务器获取token成功");
                _this.setStorage(resp.data);
                return resolve(resp.data);
              }
            },
            fail(res) {
              console.log("从服务器获取token失败02:", resp.msg);
              return reject(res);
            }
          });
        }
      })
    })
  },
  getStorage() {
    return wx.getStorageSync(config.TOKEN_KEY);
  },
  setStorage(data) {
    wx.setStorageSync(config.TOKEN_KEY, data);
  },
  removeStorage() {
    wx.removeStorageSync(config.TOKEN_KEY);
  }
};

module.exports = token;